<template>
    <div id="clickMap"></div>
</template>

<script>
	import mapConfig from "../../assets/json/mapConfig.json";
	import gpsTransformation from "../../assets/js/map/gpsTransformation";

    export default {
        mixins:[gpsTransformation],
        props:{
          showPoint:{
              type:[String,Array],
              default:""
          },
		  isClick:{
			  type:Boolean,
			  default:true
		  },
            showLine:{
               type:Array,
                default:null
            }
        },
        data() {
            return {
                map: null,
                layer: null,
                clickPoint:""
            };
        },
        watch:{
            showPoint(newVal,oldVal){
				/*if(typeof newVal =='string'){
					this.clickPoint=newVal;
				}*/
                this.addToMap();
            },
            showLine:{
                handler(newVal, oldVal) {
                   this.addLine();
                },
                deep: true
            }
        },
        methods: {
            initMap() {
                let map = L.map("clickMap", {
                    minZoom: 3,
                    maxZoom: 18,
                    center: mapConfig.center,
                    zoom: mapConfig.zoom,
                    zoomControl: false,
                    attributionControl: false,
                    crs: L.CRS.EPSG3857
                });

                L.control.zoom({
                    position: 'bottomright'
                }).addTo(map);

                //控制地图底图
                var baseLayers = {
                    "高德地图": L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', { subdomains: "1234" }),
                    "高德影像": L.layerGroup(
                        [
                            L.tileLayer('http://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', { subdomains: "1234" }),
                            L.tileLayer('http://webst0{s}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8', { subdomains: "1234" })
                        ]
                    ),
                    //天地图tk可以换成自己申请的key
                    "天地图": L.layerGroup([
                        L.tileLayer('http://t{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] }),
                        L.tileLayer('http://t{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] })
                    ]),
                    "天地图影像": L.layerGroup([
                        L.tileLayer('http://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] }),
                        L.tileLayer('http://t{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] })
                    ]).addTo(map),
                    "天地图地形": L.layerGroup([
                        L.tileLayer('http://t{s}.tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] }),
                        L.tileLayer('http://t{s}.tianditu.gov.cn/cta_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cta&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=56b81006f361f6406d0e940d2f89a39c', { subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'] })
                    ]),

                    "Google地图": L.tileLayer('http://mt1.google.cn/vt/lyrs=m@207000000&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=Galile'),
                    "Google影像": L.layerGroup([
                        L.tileLayer('http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&gl=CN&x={x}&y={y}&z={z}&s=Gali'),
                        L.tileLayer('http://mt1.google.cn/vt/imgtp=png32&lyrs=h@207000000&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&s=Galil')
                    ]),

                    "GeoQ ": L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}'),
                    "GeoQ 藏蓝": L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'),
                    "GeoQ 灰": L.tileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}')
                };

                L.control.layers(baseLayers, {}, { position: "topright" }).addTo(map);

                this.map = map; //data上需要挂载
				if(this.isClick){
				 this.initMapClick();
				}

                //加载图层
                this.layer = L.layerGroup().addTo(map);
                if(this.showPoint){
                    this.addToMap();
                }

                if(this.showLine){
                    this.addLine();
                }

            },
            initMapClick(){
                var self = this;
              this.map.on('click',function (evt) {
                  var value = self.wgs84togcj02(evt.latlng.lat,evt.latlng.lng);
                  self.clickPoint = value[1]+","+value[0];
				  self.addClickToMap();
                 self.$emit("setValue",self.clickPoint);
              });
            },
			addClickToMap(){
				if(this.layer){
				  this.layer.clearLayers();
				}
				var startIcon = L.icon({
				  iconUrl: require("../../assets/images/map/endPoint.png"),
				  iconSize: [36, 36]
				});

				if(this.clickPoint){
				   var point = this.clickPoint.split(",");
				   var tPoint = this.gcj02towgs84(point[0],point[1]);
				    L.marker(tPoint, { icon: startIcon}).addTo(this.layer);
				}
			},
            addToMap(){
                if(this.layer){
                  this.layer.clearLayers();
                }
                var startIcon = L.icon({
                  iconUrl: require("../../assets/images/map/endPoint.png"),
                  iconSize: [36, 36]
                });
                debugger
                if(Array.isArray(this.showPoint)){//数组点
					 for(var i = 0;i < this.showPoint.length;i++){
						 var point = this.showPoint[i].split(",");
						 var tPoint = this.gcj02towgs84(point[0],point[1]);
						  L.marker(tPoint, { icon: startIcon}).addTo(this.layer);
						  if(i == 0){
                              this.map.setView(tPoint,11)
                             // this.map.setZoom(11)
                          }
					 }
                }else if(typeof this.showPoint == 'string'){
					var point = this.showPoint.split(",");
                    var tPoint = this.gcj02towgs84(point[0],point[1]);
					 L.marker(tPoint, { icon: startIcon}).addTo(this.layer);
					 this.map.setView(tPoint)
					 //this.map.setZoom(16)
				}
            },
            addLine(){
                var self = this;
                if(!this.showLine && this.showLine.length == 0){
                    return;
                }
                if(this.layer){
                    this.layer.clearLayers();
                }
                var line = [];
                for(var i = 0;i < this.showLine.length;i++){
                    var point = this.gcj02towgs84(this.showLine[i][0],this.showLine[i][1]);
                    line.push(point)
                }
                var polyline = L.polyline(line, {color: 'red'}).addTo(self.layer);

                //加载起止点坐标
                var startIcon = L.icon({
                    iconUrl: require("../../assets/images/map/startPoint.png"),
                    iconSize: [36, 36]
                });

                var endIcon = L.icon({
                    iconUrl: require("../../assets/images/map/endPoint.png"),
                    iconSize: [36, 36]
                });
                let startPoint = L.marker(line[0], { icon: startIcon}).bindPopup('起点',{
                    offset: L.point(0, 0)
                }).addTo(self.layer);
                this.map.setView(line[0])
                this.map.setZoom(11)
                let endPoint = L.marker(line[line.length-1], { icon: endIcon}).bindPopup('终点',{
                    offset: L.point(0, 0)
                }).addTo(self.layer);
            },

			//获取当前坐标
			getCurrentLocation(){
				var loc=[];
				var _this=this;
				navigator.geolocation.getCurrentPosition(
					function (position) {
						console.log("当前位置：",position)
						loc=[position.coords.longitude,position.coords.latitude]
						if(this.map){
							//this.map.setView(loc,11)
						}
					},
					function (e) {
						_this.$message.warning("无法获取当前位置!")
					   throw(e);
					}
				)
			}
        },
		mounted() {
		    this.initMap();
			this.getCurrentLocation()
		},
    };
</script>
<style scoped lang="scss">
    #clickMap {
        width:100%;
        height:100%;
		flex: 1;
    }
	/deep/ .leaflet-top, 
	/deep/ .leaflet-bottom{
		z-index: 2222;
	}
</style>
